/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import i18n from '@src/locales'
import { PaymentMethodLabelEnum } from '@model/enum/LabelEnum'

/* image */
import { getOssUrl, getLocalesOssUrl } from '@src/util/assets'
const ZFB_IMG = getOssUrl('/task/pay.png')
const ZFB_QRCODE_IMG = getOssUrl('/task/payOnline.png')
const WX_QRCODE_IMG = getOssUrl('/task/weiChat.png')
const BANK_IMG = getLocalesOssUrl('/task/bankCard.png')

const PAY_SUCCESS_IMG = getLocalesOssUrl('/task/paySuccess.png')

/* utils */
import { getRootWindow } from '@src/util/dom'
export default {
  inject: ['initData'],
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    },
    allowApprove: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {},
      paymentInfo: {}
    }
  },
  computed: {
    /** 
    * @description 工单详情数据
    */
    task() {
      return this.initData?.task || {};
    },
    /** 
    * @description 回执设置
    */
    receiptConfig() {
      return this.initData.receiptConfig || {};
    },
    /** 
    * @description 工单类型设置
    */
    taskType() {
      return this.initData.taskType || {};
    },
    /** 
    * @description 非自定义回执
    * 默认工单且未开启自定义回执(老功能)
    */
    notCustom() {
      return !this.receiptConfig?.customReceipt && this.task.templateId == '1';
    },
    /** 
    * @description 显示备件
    */
    showSparepart() {
      let { showSparepart } = this.taskType?.options || {};
      return this.notCustom || (!this.notCustom && showSparepart);
    },
    /** 
    * @description 显示服务项目
    */
    showService() {
      let { showService } = this.taskType?.options || {};
      return this.notCustom || (!this.notCustom && showService);
    },
    /** 
    * @description 显示物料核销
    */
    showMaterialVerifyEliminate() {
      let { showMaterialVerifyEliminate } = this.taskType?.options || {};
      return this.notCustom || (!this.notCustom && showMaterialVerifyEliminate);
    },

    // 是否开启云仓灰度
    isCloudwarehouse() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskCloudWarehouse || false
    },
    
    /** 
    * @description 显示物料核销 并且添加了数据
    */
    isMaterialVerifyEliminate() {
      return this.showMaterialVerifyEliminate && this.form?.materialVerifyEliminate?.length > 0
    },
    /** 
    * @description 显示物料返还
    */
    showMaterialReturn() {
      let { showMaterialReturn } = this.taskType?.options || {};
      return this.notCustom || (!this.notCustom && showMaterialReturn);
    },
    /** 
    * @description 显示物料返还 并且添加了数据
    */
    isMaterialReturn() {
      return this.showMaterialReturn && this.form?.materialReturn?.length > 0
    },
    /** 
    * @description 备件费用
    */
    sparepartTotal() {
      let { sparepart } = this.form;
      let total = 0;
      if(!this.isFreeSparePartFee) {
        if (Array.isArray(sparepart)) {
          sparepart.forEach(item => {
            total += item.number * item.salePrice;
          })
        }
      }

      return total.toFixed(2);
    },
    /** 
    * @description 服务费用
    */
    serviceTotal() {
      let { serviceIterm } = this.form;
      let total = 0;
      if(!this.isFreeServiceFee) {
        if (Array.isArray(serviceIterm)) {
          serviceIterm.forEach(item => {
            if (this.isServiceItemDiscountSettings) { 
              total += item.number * item.salePrice - item.reductionFee;
            }else if(item.exchangeRate) {
              total += item.number * item.salePrice * item.exchangeRate;
            }else {
              total += item.number * item.salePrice 
            }
          })
        }
      }

      return total.toFixed(2);
    },
    /** 
    * @description 是否配置了质保字段
    */
    hasQuality() {
      return this.taskFields.some(item => item.fieldName === 'quality')
    },
    /** 
    * @description 物料核销费用
    */
    materialTotal() {
      // 按照产品需求：物料先用质保的配置 后续是否需要添加物料的配置待定
      let { materialVerifyEliminate } = this.form;
      let total = 0;
      if (Array.isArray(materialVerifyEliminate)) {
        materialVerifyEliminate.forEach(item => {
          // TODO 国际化待办
          let calculateCost = this.hasQuality && this.isFreeMaterialFee && item.warrantyStatus === '保内'
          if(!calculateCost) {
             // TODO 国际化灰度开启
            if(item.exchangeRate) {
              total += item.number * item.salePrice * item.exchangeRate; 
            }else {
              total += item.number * item.salePrice;
            }
          }
        })
      }

      return total.toFixed(2);
    },
    /** 
    * @description 费用总计
    */
    totalExpense() {
      let partExpense = Number(this.sparepartTotal);
      let serviceExpense = Number(this.serviceTotal);
      let materialTotal = Number(this.materialTotal);
      let disExpense = Math.abs(this.form.disExpense);

      // return (partExpense + serviceExpense - disExpense).toFixed(2);
      return (materialTotal + partExpense + serviceExpense - disExpense).toFixed(2);
    },
    /** 
    * @description 费用合计数据
    */
    totalData() {
      let {sparepartTotal, serviceTotal, materialTotal, totalExpense } = this;
      let { disExpense } = this.form;
      
      return [{
        sparepartTotal,
        serviceTotal,
        materialTotal,
        disExpense,
        totalExpense
      }]
    },
    /** 
    * @description 是否支付成功
    */
    isPaySuccess() {
      return this.initData?.isPay || false;
    },
    /** 
    * @description 在线支付成功
    */
    payOnlineSuccess() {
      // TODO 国际化待办
      return this.isPaySuccess && this.paymentMethod == '在线支付-支付宝';
    },
    /**
    * @description 非自定义回执字段
    * 默认显示回执内容、系统附件、备件、服务项目
    */
    notCustomFields() {
      let { receiptAttNotNull, sparepartNotNull, serviceNotNull, receiptSignNotNull } = this.taskType?.options || {};

      return [{
        displayName: i18n.t('common.form.type.receiptContent'),
        fieldName: 'receiptContent',
        formType: 'textarea',
        isNull: 0,
        isSystem: 1
      }, {
        displayName: i18n.t('common.form.type.receiptAttachment'),
        fieldName: 'receiptAttachment',
        formType: 'receiptAttachment',
        isNull: receiptAttNotNull ? 0 : 1,
        isSystem: 1
      }, {
        displayName: i18n.t('common.base.sparePart'),
        fieldName: 'sparepart',
        formType: 'sparepart',
        isNull: sparepartNotNull ? 0 : 1,
        isSystem: 1
      }, {
        displayName: i18n.t('common.form.type.serviceIterm'),
        fieldName: 'serviceIterm',
        formType: 'serviceIterm',
        isNull: serviceNotNull ? 0 : 1,
        isSystem: 1
      }, {
        displayName: i18n.t('common.form.type.systemAutograph'),
        fieldName: 'systemAutograph',
        formType: 'systemAutograph',
        isNull: receiptSignNotNull ? 0 : 1,
        isSystem: 1
      }]
    },

    // 服务项目折扣灰度
    isServiceItemDiscountSettings() {
      const RootWindow = getRootWindow(window)
      return Boolean(RootWindow.grayAuth?.serviceItemDiscountSettings)
    },
    // 是否开放服务商查看服务项目和物料的价格信息
    serviceProviderShowPrice() {
      try {
        const RootWindow = getRootWindow(window);
        const InitData = RootWindow._init ? JSON.parse(RootWindow._init) : {};
        return InitData.serviceProviderShowPrice ?? true;
      } catch (error) {
        return true;
      }
    },
  },
  methods: {
    // 获取支付方式的多语言label
    getPaymentMethodLabel(text) {
      return PaymentMethodLabelEnum[text] || text
    },
    /** 
    * @description 支付成功icon
    */
    getPaySuccessImg() {
      return PAY_SUCCESS_IMG;
    },
    /**
    * @description 获取支付方式对应icon
    */
    getPaymentMethodImg() {
      // TODO 国际化待办
      if (this.paymentMethod == '在线支付-支付宝') return ZFB_IMG;
      if (this.paymentMethod == '支付宝收款码') return ZFB_QRCODE_IMG;
      if (this.paymentMethod == '微信收款码') return WX_QRCODE_IMG;
      if (this.paymentMethod == '银行卡收款') return BANK_IMG;

      return '';
    },
    /**
    * @description 获取在线支付详情
    */
    getPaymentMethodDetail() {
      TaskApi.getPaymentDetail({taskId: this.task.id}).then(res => {
        if (res.success && res.result) {
          this.paymentInfo = res.result;
        }
      }).catch(err => console.error(err))
    },
  }
}
